package com.leetcode.two_pointers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Dennis Li
 * @date 2020/9/23 17:20
 */
public class FourSum_18 {

    public static void main(String[] args) {
        FourSum_18 solution = new FourSum_18();
        int[] nums = {0, 0, 0, 0};
        List<List<Integer>> lists = solution.fourSum(nums, 0);
        System.out.println(lists.toString());
    }

    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int m = 0; m < nums.length - 3; m++) {
            // 这个只是对于等于0的情况的一种特殊处理
//            if (nums[m] > target) break;
            if (m > 0 && nums[m - 1] == nums[m]) m++;
            threeSum(nums, target - nums[m], m, res);
        }
        return res;
    }

    public void threeSum(int[] nums, int target, int m, List<List<Integer>> res) {
        for (int k = m + 1; k < nums.length - 2; k++) {
//            if (nums[k] > target - nums[m]) break;
            if (k > m + 1 && nums[k] == nums[k - 1]) continue;
            twoSum(nums, target - nums[k], m, k, res);
        }
    }

    public void twoSum(int[] nums, int target, int m, int k, List<List<Integer>> res) {
        int i = k + 1, j = nums.length - 1;
        while (i < j) {
            int sum = nums[i] + nums[j];
            int left = nums[i], right = nums[j];
            if (sum > target) {
                while (i < j && nums[j] == right) j--;
            } else if (sum < target) {
                while (i < j && nums[i] == left) i++;
            } else {
                res.add(Arrays.asList(nums[m], nums[k], nums[i], nums[j]));
                while (i < j && nums[j] == right) j--;
                while (i < j && nums[i] == left) i++;
            }
        }
    }
}
